<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input v-model="params.name" clearable placeholder="请输入内容" class="search-main" @clear="showAllenterPrise" />
      <el-button type="primary" @click="searchEnterPrise">查询</el-button>
    </div>
    <div class="create-container">
      <el-button type="primary" @click="$router.push('/addEnterPrise')">添加企业</el-button>
    </div>
    <auth-btn btn-pers="666">
      <button>666</button>
    </auth-btn>
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="enterPriseList" @expand-change="expandChange">
        <el-table-column type="expand">
          <template #default="{row}">
            <el-table :data="row.rentList">
              <el-table-column label="租赁楼宇" width="320" prop="buildingName" />
              <el-table-column label="租赁起始时间" prop="startTime" />
              <el-table-column label="合同状态" prop="status">
                <template #default="obj">
                  <el-tag :type="forMatterTag(obj.row.status)">{{ forMatter(obj.row.status) }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180">
                <template #default="scope">
                  <el-button size="mini" type="text">续租</el-button>
                  <el-button size="mini" :disabled="scope.row.status===3" type="text" @click="outRent(scope.row.id)">退租</el-button>
                  <el-button size="mini" :disabled="isDelete(scope.row.status)" type="text">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" />
        <el-table-column label="企业名称" width="320" prop="name" />
        <el-table-column label="联系人" prop="contact" />
        <el-table-column
          label="联系电话"
          prop="contactNumber"
        />
        <el-table-column label="操作">
          <template #default="obj">
            <el-button size="mini" type="text" @click="addContract(obj.row.id)">添加合同</el-button>
            <el-button size="mini" type="text" @click="DetailEnterprise(obj.row.id)">查看</el-button>
            <el-button size="mini" type="text" @click="editEnterPrise(obj.row.id)">编辑</el-button>
            <el-button size="mini" type="text" :disabled="obj.row.existContractFlag?true:false">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination
        :current-page="params.page"
        :page-size="params.pageSize"
        :total="total"
        layout="total, prev, pager, next"
        @current-change="handleCurrentChange"
      />
    </div>
    <el-dialog
      title="提示"
      :visible="dialogVisible"
      width="40%"
      @close="closeDialog"
      @open="openBuilding"
    >
      <div class="form-container">
        <el-form ref="addForm" :model="rentForm" :rules="rentRules" label-position="top">
          <el-form-item label="租赁楼宇" prop="buildingId">
            <el-select v-model="rentForm.buildingId" placeholder="请选择">
              <el-option
                v-for="item in rentBuildingList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="租赁起止日期" prop="rentTime">
            <el-date-picker
              v-model="rentForm.rentTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
          <el-form-item label="租赁合同" prop="contractId">
            <el-upload
              action="#"
              :http-request="Upload"
            >
              <el-button size="small" type="primary" plain>上传合同文件</el-button>
              <div slot="tip" class="el-upload__tip">支持扩展名：.doc .docx .pdf, 文件大小不超过5M</div>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getListEnterPriseAPI, addEnterPriseRentAPI, getRentListAPI, outRentAPI } from '@/api/park'
import { getRentBuidingAPI } from '@/api/building'
import { UploadAPI } from '@/api/commont'
export default {
  data() {
    return {
      params: {
        name: '',
        page: 1,
        pageSize: 2
      },
      enterPriseList: [],
      rentBuildingList: [],
      total: 0,
      // 合同添加显示
      dialogVisible: false,
      rentForm: {
        buildingId: null, // 楼宇id
        contractId: null, // 合同id
        contractUrl: '', // 合同Url
        enterpriseId: null, // 企业名称
        type: 0, // 合同类型
        rentTime: [] // 合同时间
      },
      rentRules: {
        buildingId: [
          { required: true, message: '请选择楼宇', trigger: 'change' }
        ],
        rentTime: [
          { required: true, message: '请选择租赁日期', trigger: 'change' }
        ],
        contractId: [
          { required: true, message: '请上传合同文件', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    // 获取企业数据
    this.getListEnterPrise()
  },
  methods: {
    async getListEnterPrise() {
      const res = await getListEnterPriseAPI(this.params)
      this.enterPriseList = res.data.rows.map(item => {
        return {
          ...item,
          rentList: []
        }
      })
      console.log(res.data)
      this.total = res.data.total
    },
    // 显示合同弹出框
    addContract(id) {
      this.dialogVisible = true
      // 添加企业id
      this.rentForm.enterpriseId = id
    },
    // 关闭弹出框
    closeDialog() {
      this.dialogVisible = false
    },
    // 调用楼宇接口
    async openBuilding() {
      const res = await getRentBuidingAPI()
      this.rentBuildingList = res.data
    },
    // 文件表单接口
    async Upload(res) {
      // 1.获取到file文件
      const { file } = res
      // 2.创建formData
      const fd = new FormData()
      // 3.根据接口需要进行添加
      fd.append('file', file)
      fd.append('type', 'contract')
      // 4.向上传文件接口发送请求
      const _res = await UploadAPI(fd)
      console.log(_res)
      // 5.将数据存入rentForm中
      this.rentForm.contractId = _res.data.id
      this.rentForm.contractUrl = _res.data.url
      console.log(this.rentForm)
    },
    // 添加合同
    addConfirm() {
      this.$refs.addForm.validate(async valid => {
        if (valid) {
          const { buildingId, contractId, contractUrl, type, enterpriseId } = this.rentForm
          const data = {
            buildingId,
            contractId,
            contractUrl,
            type,
            enterpriseId,
            startTime: this.rentForm.rentTime[0],
            endTime: this.rentForm.rentTime[1]
          }
          await addEnterPriseRentAPI(data)
          // 清空表单和手动清空
          this.rentForm = []
          this.$refs.addForm.resetFields()
          // 提示框
          this.$message.success('添加合同成功')
          // 重新加载
          this.getListEnterPrise()
          this.dialogVisible = false
        }
      })
    },
    // 展示合同
    async expandChange(row, rows) {
      // row 所点击展开的那一行数据
      // rows 全部展开的数据
      // 首先先取出id通过id发起请求
      // 如果rows里面包括了row那么就发情请求
      const isexist = rows.find(item => item.id === row.id)
      if (isexist) {
        const res = await getRentListAPI(row.id)
        // 将获取到的数据添加到enterPriseList企业列表里面
        // eslint-disable-next-line require-atomic-updates
        row.rentList = res.data
      }
    },
    // 合同显示状态
    forMatter(id) {
      const TYPEMAP = {
        0: '待生效',
        1: '生效中',
        2: '已到期',
        3: '已退租'
      }
      return TYPEMAP[id]
    },
    // 合同的tag状态
    forMatterTag(id) {
      const TYPEMAP = {
        0: '',
        1: 'success',
        2: 'warning',
        3: 'danger'
      }
      return TYPEMAP[id]
    },
    // 查看企业详情
    DetailEnterprise(id) {
      // 路由跳转到企业详情
      this.$router.push({
        path: '/detailEnterPrise',
        query: {
          id
        }
      })
    },
    // 退租
    async outRent(id) {
      this.$confirm('此操作将把合同退租, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await outRentAPI(id)
        this.$message({
          type: 'success',
          message: '退租成功!'
        })
        this.getListEnterPrise()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    isDelete(statu) {
      if (statu === 0 || statu === 1) {
        this.isDisable = true
        return true
      }
      this.isDisable = false
      return false
    },
    // 处理分页
    handleCurrentChange(page) {
      this.params.page = page
      this.getListEnterPrise()
    },
    // 搜索
    searchEnterPrise() {
      this.params.page = 1
      this.getListEnterPrise()
    },
    // 删除搜索框的数据
    showAllenterPrise(value) {
      console.log(value)
      this.getListEnterPrise()
    },
    // 编辑页面
    editEnterPrise(id) {
      // 携带id进行传参
      this.$router.push({
        path: '/editEnterPrise',
        query: {
          id
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.department-container {
  padding: 10px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  ;
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}
.create-container{
  margin: 10px 0px;
}
.page-container{
  padding:4px 0px;
  text-align: right;
}
.form-container{
  padding:0px 80px;
}
</style>
